package com.bistu.openlab.uofspreadsheet.xmlparse;

import java.util.List;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.bistu.openlab.uofspreadsheet.model.SheetCell;
import com.bistu.openlab.uofspreadsheet.model.SheetRow;
import com.bistu.openlab.uofspreadsheet.util.TypeConvertor;
import com.bistu.openlab.uofspreadsheet.util.XmlDomHelper;

/*
 *@author xiaoguang.gao@oracle.com
 *@version 2013-5-9 
 */
public class SheetRowParse implements IXmlParse<SheetRow>{
	private static SheetRowParse parse = new SheetRowParse();
	private SheetRowParse(){}
	/**
	 * 
	 * @return
	 */
	public static SheetRowParse getInstance(){
		return parse;
	}

	@Override
	public SheetRow readFromElement(Element root) {
		SheetRow row = null;
		if(root!=null&&root.getName().equals("行_E7F1")){
			row = new SheetRow();
			String rowNumStr = XmlDomHelper.GetAttributeValue(root, "行号_E7F3");
			row.setRowNum(TypeConvertor.GetInt(rowNumStr));
			//cells
			SheetCellParse cellParse = SheetCellParse.getInstance();
			List<Element> cellEleList = root.selectNodes("表:单元格_E7F2");
			if(cellEleList!=null&&cellEleList.size()>0){
				for(Element cellEle : cellEleList){
					row.addSheetCell(cellParse.readFromElement(cellEle));//add a cell
				}
			}
		}
		return row;
	}

	@Override
	public Element writeToElement(SheetRow obj) {
		Element root = null;
		if(obj!=null){
			root = DocumentHelper.createElement("表:行_E7F1");
			root.addAttribute("行号_E7F3", obj.getRowNum()+"");
			
			SheetCellParse cellParse = SheetCellParse.getInstance();
			if(obj.getCellList()!=null&&obj.getCellList().size()>0)
			{
				for(SheetCell cell : obj.getCellList()){
					Element cellEle = cellParse.writeToElement(cell);
					if(cellEle!=null)root.add(cellEle);
				}
			}
		}
		return root;
	}

}
